<?php
class LoginController extends AppController {
	public $helpers = array('Html', 'Form');
	
	public function login(){
		//neu da dang nhap
		if($this->Session->check("AdminLogin")){
			//show thong bao loi da dang nhap roi, chuyen ve trang chu
			$this->Session->setFlash('Already login!', 'default', array('class' => 'alert alert-info'));
			return $this->redirect(array('controller' => 'posts', 'action' => 'index'));
		}
		
		//xoa session search normal neu ton tai
		if($this->Session->check('SearchCondition')){
			$this->Session->delete('SearchCondition');
		}
	}
	
	public function  doLogin(){
		$this->loadModel('Admin');
		if($this->request->is('post')){
			//lay gia tri textbox username
			$username = $this->request->data['txtUsername'];
			
			//kiem tra username co ton tai khong
			$admin = $this->Admin->find('first', array('conditions' => array('Admin.Username' => $username)));
			//neu khong ton tai username do, show thong bao loi va hien lai trang login
			if(!$admin){
				$this->Session->setFlash('Username or password incorrect!', 'default', array('class' => 'alert alert-danger'));
				return $this->render("/login/login");
			}
			
			//lay gia tri textbox password
			$password = $this->request->data['txtPassword'];
			
			//lay gia tri password cua user trong database
			$pass = $admin['Admin']['Password'];
			
			//neu password da nhap = password trong database
			if($password == $pass){
				//set session user dang nhap, thong bao dang nhap thanh cong va chuyen ve trang chu
				$this->Session->write('AdminLogin', $admin);
				$this->Session->setFlash('Login success! Welcome '.$admin['Admin']['Fullname'], 'default', array('class' => 'alert alert-success'));
				return $this->redirect(array('controller' => 'posts', 'action' => 'index'));
			}
			
			//neu password khong giong nhau, show thong bao loi va hien lai trang login
			$this->Session->setFlash('Username or password incorrect!', 'default', array('class' => 'alert alert-danger'));
			return $this->render("/login/login");
		}
	}
	
	public function logout(){
		//neu da login roi
		if($this->Session->check('AdminLogin')){
			//delete session user login, show thong bao logout thanh cong
			$this->Session->delete("AdminLogin");
			$this->Session->setFlash('Logout success!', 'default', array('class' => 'alert alert-success'));
		}else{
			//neu chua login, show thong bao loi chua login
			$this->Session->setFlash('You are not logged in!', 'default', array('class' => 'alert alert-danger'));
		}
		//chuyen ve trang chu
		return $this->redirect(array('controller' => 'posts', 'action' => 'index'));
	}
}